<template>
  <div>
    <div class="list-btn">
      角色名称:<Input v-model.trim="params.name" placeholder="请输入角色名称" style="width: 200px" clearable @keyup.enter.native="getList(url)" />

    </div>
    <div class="list-btn">
      <Button type="primary" @click="getList(url,'refresh')">搜索</Button>
      <Button type="primary" style="margin-left:10px;" @click="resetValidate('formRole');showModal.isShow = true;type = '增加';">新增角色</Button>
    </div>

    <page-list :listTitle="listTitle" :list="list" :loading="loading" @selectItem="ids = $event;"></page-list>
    <page-button :current="params.pageCurrent"  :total="total" @changePageNum="params.pageCurrent = $event; getList(url)" @changePageSize="params.pageLimit = $event; getList(url)"></page-button>

    <!--编辑角色-->
    <Modal
      v-model="showModal.isShow"
      title="编辑角色"
      width="500px"
      :closable="true"
      :style="{textAlign:'left'}">
      <Form ref="formRole" :rules="ruleValidate" :model="formRole" :label-width="80">
        <FormItem label="角色名称" prop="name">
          <Input v-model="formRole.name" placeholder="请输入" style="width:200px"></Input>
        </FormItem>
       <!-- <FormItem label="角色类型" prop="roleType">
          <Select clearable v-model="formRole.roleType" placeholder="请选择" style="width:200px">
            <Option v-for="item in roleTypeList" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
        </FormItem>

        <FormItem label="启用状态" prop="useable">
          <Select clearable v-model="formRole.useable" placeholder="请选择" style="width:200px">
            <Option v-for="item in useableList" :value="item.id" :key="item.id">{{item.name}}</Option>
          </Select>
        </FormItem>-->
        <div style="margin-left: 350px;">
          <Button @click="cancel">取消</Button>
          <Button type="primary" @click="ok">确定</Button>
        </div>
      </Form>
    </Modal>

    <!--权限分配-->
    <Modal
      v-model="showModal.permission"
      title="权限分配"
      width="600px"
      :closable="true">
      <Tree
        :data="treeData"
        show-checkbox
        @on-check-change="selectItem"
        ref="tree"
        style="height:600px;width:100%;overflow: auto;"></Tree>
      <div style="margin-left: 350px;">
        <Button @click="closed">取消</Button>
        <Button type="primary" @click="submit">确定</Button>
      </div>
    </Modal>

  </div>
</template>
<script>
  import listMixin from '../../mixin/list'
  import pageList from '../../template/listTemplate'
  import pageButton from '../../template/pageBtnTemplate'
  import confirmDialog from '../../template/confirmDialogTemplate'
  export default {
    mixins:[listMixin],
    components: {
      pageList,
      pageButton,
      confirmDialog
    },
    data () {
      return {
        tag: {
          'title': '角色管理',
          'path': '/work/role/list'
        },
        listTitle: [
          {
            title: '角色名称',
            key: 'name',
            align:'center',
            minWidth:120
          },
         /* {
            title: '角色类型',
            key: 'roleType',
            align:'center',
            minWidth:120,
            render: (h, params) => {//角色类型 1系统指定角色 0临时角色
              let texts = '';
              switch (params.row.roleType) {
                case '0':
                  texts = '临时角色';
                  break;
                case '1':
                  texts = '系统指定角色';
                  break;
              }
              return h('div', {

              }, texts)
            }
          },*/

          {
            title: '创建时间',
            key: 'createTime',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              let len = (params.row.createTime).length;
              let text = (params.row.createTime).substr(0,len-2)
              return h('div', text)
            }
          },
          {
            title: '修改时间',
            key: 'updateTime',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              let text = '—';
              if(params.row.updateTime){
                let len = (params.row.updateTime).length;
                text = (params.row.updateTime).substr(0,len-2)
              }

              return h('div', text)
            }
          },
          {
            title: '操作人',
            key: 'updatorName',
            align:'center',
            minWidth:100,
            render:(h,params) => {
              return h('div',params.row.updatorName?params.row.updatorName:'—')
            }
          },
          {
            title: '状态',
            key: 'useable',
            minWidth:120,
            align:'center',
            render: (h, params) => {// 0有效1停用
              let texts = '';
              switch (params.row.useable) {
                case '0':
                  texts = '有效';
                  return h('Button', {
                    props: {
                      size:'small',
                      type: 'success'
                    },
                  }, texts)
                  break;
                case '1':
                  texts = '停用';
                  return h('Button', {
                    props: {
                      size:'small',
                      type: 'warning'
                    },
                  }, texts)
                  break;
              }

            },
          },
          {
            title: '操作',
            key: 'action',
            align:'center',
            width: 300,
            render: (h, params) => {
              let text = '';
              let useable = '';
              if(params.row.useable == '1'){
                text = '启用';
                useable = '0';
              }else{
                text = '停用'
                useable = '1';
              }
              return h('div', [
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showModal.isShow = true;
                      this.formRole = JSON.parse(JSON.stringify(params.row));
                      console.log(params)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: `<p>是否${text}该用户?</p>`,
                        onOk: () => {
                          let data = {};
                          data.id = params.row.id;
                          data.useable = useable;

                          this.stopRole(data);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, text),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showModal.permission = true;
                      this.formRole = JSON.parse(JSON.stringify(params.row));
                      this.getPermissionList(params.row.id);
                      console.log(params)
                    }
                  }
                }, '权限分配'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: `<p>是否删除该用户?</p>`,
                        onOk: () => {
                          let data = {};
                          data.id = params.row.id;
                          this.delItem('/sysRole/discard', data);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, '删除'),
              ]);
            }
          },
        ],
        treeData:[],
        checkedList: [],
        url: '/sysRole/list',
        nameListUrl: '',
        params: {
          pageCurrent: 1,
          pageLimit: 10
        },
        loaded: true,
        roleTypeList: [
          {
            id: '0',
            name: '非流程角色'
          },
          {
            id: '1',
            name: '流程角色'
          }
        ],
        useableList: [
          {
            id: '0',
            name: '有效'
          },
          {
            id: '1',
            name: '停用'
          }
        ],
        formRole: {
          useable:'0',
          roleType:'0',
        },
        showModal: {
          isShow: false,
          permission: false
        },
        ruleValidate: {
          name: [
            { required: true, message: '请填写角色名称', trigger: 'blur' }
          ],
         /* roleType: [
            { required: true, message: '请选择角色类型', trigger: 'blur' }
          ],
          useable: [
            { required: true, message: '请选择启用状态', trigger: 'blur'}
          ]*/
        },
        type:'编辑',

      }
    },
    methods: {

      submit() {
        // let checked = this.$refs['tree'].getCheckedKeys()
        const checkedNode = this.$refs['tree'].getCheckedAndIndeterminateNodes(false, true)
        const btnList = []
        const menuList = []
        const idArr = []

        console.log(checkedNode,'checkedNode')

        checkedNode.forEach((val, index) => {

          const children = val.children

          idArr.push(val.id)
          if (children && children.length !== 0) {

            // 父节点
            menuList.push(val.id)
          } else {
            // 叶子节点
            btnList.push(val.id)
          }
        })
        console.log(menuList,'children')

        var hash = {}
        var i = 0
        var res = []
        const menuParentId = []
        checkedNode.forEach(function(item){
          menuParentId.push(item.id);
          res.push({'meunId':item.id,'meno':''})
        })
        /*checkedNode.forEach(function(item) {
          var menuId = item.menuId;
          const hasChildrens = item.childrens;
          const isRoot = item.parentId === '0' ? true : false

          if (!isRoot) {
            // 菜单节点 并且非功能菜单
            if (!hasChildrens) {
              // 叶子节点
              if (hash[menuId]) {
                res[hash[menuId] - 1].meno.push(item.id)
              } else {
                hash[menuId] = ++i && res.push({
                  meno: [item.id],
                  meunId: menuId
                })
              }

            } else {
              menuParentId.push(item.id)
            }
          }
        })
        console.log(res,'item.res.meunId')

        res.forEach((val, index) => {
          console.log(val,'item.res')

          if (!val.meunId) {
            const menuList = val.meno
            menuList.forEach((cval, index) => {

              res.push({
                meunId: cval,
                meno: ''
              })
            })
            res.splice(index, 1)
          }
        })
*/
        const data = {
          roleId: this.formRole.id,
          menuParentId: menuParentId.join(','),
          menuIdList: JSON.stringify(res),
          // menuIdList: JSON.stringify(res),
        }
        console.log(data,'dataup')
        this.permissionBtn(data);
        //this.$emit('submit', data)
      },



      formatTree(parr, carr) {

        parr.forEach((val, idnex) => {
          val.title = val.name;
          val.expand = true;
          val.children = val.childrens;
          if (val.childrens.length !== 0) {
            this.formatTree(val.childrens, carr)
          } else {
            // 遍历到了根节点
            carr.forEach((cval, cindex) => {

              if (cval.menuId === val.id) {

                /*val.childrens.push(cval)
                val.children.push(cval)*/
                cval.id = `${val.id}:${cval.id}` // ${val.id}:
                cval.title = `${val.name}:${cval.name}`
              }
            })
          }
        })
      },

      selectItem(value){
        this.checkedList = value;
      },

      //权限列表
      getPermissionList(d) {
        this.$post('/sysRoleMeun/permissionList', {id:d})
          .then((res) => {
            if(res.code === 0){
              const menuList = JSON.parse(res.data.Meunlist)
              const menuListChecked = JSON.parse(res.data.roleMeunList)
              const funcList = JSON.parse(res.data.meunFuncList)
              this.formatTree(menuList, funcList)
              const checkedList = []
              const filterBtn = []
              console.log(funcList,'fun')

              menuListChecked.forEach((val, index) => {
                let meno = val.meno
                if (meno) {
                  meno = JSON.parse(val.meno)
                  meno.forEach((item) => {
                    let menooo = item.split(':');
                    if(menooo){
                      checkedList.push(menooo[1])
                    }else{
                      checkedList.push(item)
                    }
                  })
                } else {
                  checkedList.push(val.meunId)
                }
              })
              console.log(checkedList,'checkedList')
              this.checkedList = checkedList;
              const getTree = arr => arr.map(item => {
                this.checkedList.map(obj => {
                  console.log(obj,'obj')
                  if(obj == item.id){
                    item.checked = true;
                  }
                });
                var node = {
                  expand: true,
                  hasChild:item.hasChild,
                  id: item.id,
                  title: item.name,
                  name: item.name,
                  checked: item.checked,
                  children: getTree(item.childrens),
                  //childrens: getTree(item.childrens)

                }
                return node;
              })
              console.log(menuList,'menuList')
              this.treeData = getTree(menuList);

              /*const getTree = arr => arr.map(item => {
                this.checkedList.map(obj => {
                  if(obj === item.id){
                    item.checked = true;
                  }
                });
                var node = {
                  id: item.id,
                  title: item.name,
                  checked: item.checked,
                  expand: true,
                  children: getTree(item.children)
                }
                return node;
              })
              this.deptList = getTree(res.data);*/





             /* funcList.forEach((val) => {
                const item = {
                  title: val.name,
                  id: val.id,
                  selected: true,
                }
                filterBtn.push(item)

              })
              console.log(menuListChecked,'menuListChecked')
              menuListChecked.forEach((val, index) => {
                let meno = val.meno
                if (meno) {
                  meno = JSON.parse(val.meno)
                  meno.forEach((item) => {
                    checkedList.push(item)
                  })
                } else {
                  checkedList.push(val.meunId)
                }
              })
              // this.treeData = menuList
              this.checkedList = checkedList
              this.loading = false

              console.log(checkedList,'checkedList')
              const getMenu = arr => arr.map(item => {
                checkedList.map(obj => {
                  let roleCheck = obj;
                  console.log(roleCheck,'roleCheck')
                })
                return {child:getMenu(item.children)}
              })

              this.treeData = getMenu(menuList);
              console.log(this.treeData, 'treeData')
              console.log(checkedList, 'checkedList')
              console.log(filterBtn, 'filterBtn')*/


              //this.permissionList = menuList;
            }
          }, (err) => {
            console.log(err);
          })
      },
      ok() {
        console.log(this.formRole)
        let url = '';
        this.$refs['formRole'].validate((valid) => {
          if (valid) {
            let data = {
              id: this.formRole.id,
              name: this.formRole.name,
              useable: this.formRole.useable,
              roleType: this.formRole.roleType
            };
            if(this.type == '增加'){
              url = '/sysRole/append';
              //delete data.id;
            }else{
              url = '/sysRole/modify';
            }
            this.$post(url, data)
              .then((res) => {
                if(res.code === 0){
                  console.log(res.data)
                  this.showModal.isShow = false;
                  this.$Message.success(`${this.type}成功！`);
                  this.getList(this.url);
                }
              }, (err) => {
                console.log(err);
              })
          }
        })

        /**/
      },
      cancel() {
        this.showModal.isShow = false;

      },
      closed() {
        this.showModal.permission = false;

      },
      permissionBtn(data) {
        this.$post('/sysRoleMeun/saveMeunByRoleId', data)
          .then((res) => {
            if(res.code === 0){
              console.log(res.data)
              this.showModal.permission = false;
              this.$Message.success(`权限分配成功！`);
              this.getList(this.url);
            }
          }, (err) => {
            console.log(err);
          })
      },

      stopRole(item) {
        this.$post('/sysRole/modify' ,item)
          .then((res) => {
            if(res.code === 0){
              this.$Message.success(`${this.type}成功！`);
              this.getList(this.url);
            }
          }, (err) => {
            console.log(err);
          })
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .list-btn{
    margin-bottom: 5px;
    margin-right: 5px;
    display: inline-block;
  }
  .refresh-btn{
    float: right;
  }
/deep/ .ivu-modal-footer{
  display: none;
}
</style>
